const router = require('koa-router')()
const mysql = require('mysql');
const { query } = require('../public/javascripts/db')

router.prefix('/todo')

function formatTime(date) {
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    month = (month > 10 ? month : 0 + month)
    day = (day > 10 ? day : 0 + day)
    return year + '-' + month + '-' + day;
}

router.post('/submit', async (ctx, next) => {
    let options = { 'ok': false };
    let { targetName, targetPower, planName, weekTimes, allTimes, userId } = ctx.request.body;
    let sql = 'insert into target(target_name,target_power,plan_name,week_times,all_times,past_times,user_id) value(?,?,?,?,?,?,?)';
    await query(sql, [targetName, targetPower, planName, weekTimes, allTimes, 0, userId]).then(options.ok = true);
    ctx.body = options;
})

router.post('/getdata', async (ctx, next) => {
    let option = { 'ok': false };
    let { userId } = ctx.request.body;
    let sql = 'select * from target where user_id=? and past_times < all_times';
    let sql1 = 'select * from target where user_id=? and finish_time=?';
    await query(sql, [userId]).then((results) => {
        option.ok = true;
        option.allPlanList = results;
    });
    await query(sql1, [userId, formatTime(new Date())]).then((results) => {
        option.ok = true;
        option.finishLen = results.length;
    });
    ctx.body = option;
})

router.post('/update', async (ctx, next) => {
    let msg = { 'ok': false };
    let { nowTime, planId } = ctx.request.body;
    let sql = 'update target set finish_time=?,past_times=past_times+1 where plan_id=?';
    await query(sql, [nowTime, planId]).then(msg.ok = true);
    ctx.body = msg;
})

module.exports = router
